﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class Page_GoodPic_Edit : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Shove._Web.Utility.GetRequest("GoodID") != "")
            {
                int ID = Shove._Convert.StrToInt(Shove._Web.Utility.GetRequest("GoodID"), -1);

                if (ID == -1)
                {
                    PublicFunction.GoError(ErrorNumber.Unknow, "Url 参数错误", this.GetType().FullName);

                    return;
                }

                hfGoodID.Value = ID.ToString();

                labGoodName.Text = new DAL.Tables.tbl_Shop_Good().Open("GoodName_CN", "ID=" + ID, "").Rows[0]["GoodName_CN"].ToString();
            }

            BindData();
        }
    }

    #region Web 窗体设计器生成的代码

    override protected void OnInit(EventArgs e)
    {
        isRequestLogin = true;

        RequestLoginPage = this.Request.Url.AbsoluteUri;

        base.OnInit(e);
    }

    #endregion

    private void BindData()
    {
        PagedDataSource Pds = new PagedDataSource();

        DataTable dt = new DAL.Tables.tbl_Shop_GoodPic().Open("", "GoodID = " + Shove._Web.Utility.FilteSqlInfusion(hfGoodID.Value), "");

        if (dt == null)
        {
            PublicFunction.GoError(null, ErrorNumber.DataReadWrite, "数据读写错误", this.GetType().FullName);

            return;
        }

        Pds.DataSource = dt.DefaultView;
        Pds.AllowPaging = true; //开启分页
        Pds.PageSize = 9; //分页
        PSize.Text = Pds.PageSize.ToString();

        int index = int.Parse(PageIndex.Text); //当前页数
        int PageSize = Pds.PageSize;
        int TotalRecords = Pds.DataSourceCount;
        int TotalPages = TotalRecords / PageSize;//得到总页数（总记录数除以每页的记录数） 
        int ModePages = TotalRecords % PageSize;//得到取模的余数(总记录数取模每页的记录数) 

        PageColumn.Visible = (dt.Rows.Count > 0);

        if (ModePages > 0)//如果取模数不等于0，则把总页数加1 
        {
            TotalPages += 1;
        }
        if (TotalPages == 0)
        {
            TotalPages = 1;
        }
        if (index > TotalPages)
        {
            index = TotalPages;
            PageIndex.Text = index.ToString();
        }

        MaxPage.Text = TotalPages.ToString();//显示页面上的总页数 
        TotalCount.Text = TotalRecords.ToString();//显示页面上的总记录数 
        Pds.CurrentPageIndex = index - 1;

        if (index == 1)
        {
            lnkPrev.Enabled = false;
            if (TotalPages > 1)
            {
                lnkNext.Enabled = true;
            }
            else
            {
                lnkNext.Enabled = false;
            }
        }
        else
        {
            lnkPrev.Enabled = true;

            if (index == TotalPages)
            {
                lnkNext.Enabled = false;
            }
            else
            {
                lnkNext.Enabled = true;
            }
        }

        selectPage.Items.Clear(); //清除防止累加

        for (int i = 1; i <= TotalPages; i++)
        {
            selectPage.Items.Add(i.ToString());
        }

        selectPage.Items.FindByText(index.ToString()).Selected = true; //把当前页显示在列表框的第一个
        ImageList.DataSource = Pds;
        ImageList.DataBind();
    }

    protected void lnkPrev_Click(object sender, EventArgs e)
    {
        int index = int.Parse(PageIndex.Text);
        index--;
        PageIndex.Text = index.ToString();
        BindData();
    }

    protected void lnkNext_Click(object sender, EventArgs e)
    {
        int index = int.Parse(PageIndex.Text);
        index++;
        PageIndex.Text = index.ToString();
        BindData();
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        PageIndex.Text = selectPage.SelectedValue;
        BindData();
    }

    protected void ImageList_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            CheckBox cbisShow = (CheckBox)e.Item.FindControl("cbisShow");            
            TextBox tbisShow = (TextBox)e.Item.FindControl("tbisShow");            

            if (cbisShow != null)
            {
                cbisShow.Checked = Shove._Convert.StrToBool(tbisShow.Text, false);                
            }
        }
    }

    protected void ImageList_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            TextBox tbID = (TextBox)e.Item.FindControl("tbID");
            TextBox tbisShow = (TextBox)e.Item.FindControl("tbisShow");     
            CheckBox cbisShow = (CheckBox)e.Item.FindControl("cbisShow");
          
            if ((tbID != null) && (e.CommandName == "btnUpdate"))
            {
                DAL.Tables.tbl_Shop_GoodPic t_GoodPics = new DAL.Tables.tbl_Shop_GoodPic();

                t_GoodPics.IsShow.Value = cbisShow.Checked;

                if (t_GoodPics.Update("[ID] = " + tbID.Text) < 0)
                {
                    Shove._Web.JavaScript.Alert(this.Page, "更新失败");

                    return;
                }

                BindData();

                Shove._Web.JavaScript.Alert(this.Page, "图片状态更新成功");

                return;
            }
        }
    }

    protected void imgSelectAll_Click(object sender, ImageClickEventArgs e)
    {
        foreach (DataListItem item in ImageList.Items)
        {
            CheckBox cb = (CheckBox)item.FindControl("chk");

            if (cb != null)
            {
                cb.Checked = true;
            }
        }
    }

    protected void imgDelete_Click(object sender, ImageClickEventArgs e)
    {
        ArrayList imgList = new ArrayList();

        foreach (DataListItem item in ImageList.Items)
        {
            CheckBox cb = (CheckBox)item.FindControl("chk");
            HtmlInputHidden hdBiglPic = (HtmlInputHidden)item.FindControl("hdBiglPic");

            if (cb.Checked)
            {
                imgList.Add(hdBiglPic.Value);
            }
        }

        if (imgList.Count > 0)
        {
            DAL.Tables.tbl_Shop_GoodPic t_MealPics = new DAL.Tables.tbl_Shop_GoodPic();

            for (int i = 0; i < imgList.Count; i++)
            {
                if (System.IO.File.Exists(Server.MapPath(imgList[i].ToString())))
                {
                    System.IO.File.Delete(Server.MapPath(imgList[i].ToString()));
                }

                string SmallPic = imgList[i].ToString();
                SmallPic = SmallPic.Insert(SmallPic.IndexOf("."), "_Small");

                if (System.IO.File.Exists(Server.MapPath(SmallPic)))
                {
                    System.IO.File.Delete(Server.MapPath(SmallPic));
                }

                t_MealPics.Delete("GoodPic_Big = '" + imgList[i].ToString() + "'");
            }

            lblDeleteInfo.Text = "删除图片成功！";

            BindData();
        }
        else
        {
            lblDeleteInfo.Text = "请选择要删除的图片！";

            return;
        }
    }

    protected void ImageUpLoad_Click(object sender, EventArgs e)
    {
        DAL.Tables.tbl_Shop_GoodPic t_GoodPics = new DAL.Tables.tbl_Shop_GoodPic();
        int ImageCount = 0;

        Utility.XImage xImg = new Utility.XImage();

        xImg.GreateSmallImage = true;
        xImg.WatermarkText = "";        //水印文字
        xImg.WatermarkPosition = Utility.XImage.WM_TOP_RIGHT;
        xImg.WatermarkType = Utility.XImage.WM_TEXT;
        xImg.SmallImage_Width = 300;    //缩略图宽
        xImg.SmallImage_Height = 250;   //缩略图高

        string FilePath = Server.MapPath("../UpFile/Goods/");
        //string FilePath = Server.MapPath("UploadedFiles/");

        string Description = "";
        string ReturnDescription;

        foreach (string f in Request.Files.AllKeys)
        {
            // 获取提交的文件名，包含的全部的目录信息；需要提取其文件名（名字＋后缀） 
            HttpPostedFile file = (HttpPostedFile)Request.Files[f];

            string fname = file.FileName.ToLower();
            fname = fname.Replace("\\", "/");
            int lsub = fname.LastIndexOf("/");
            if (lsub >= 0)
            {
                fname = fname.Substring(lsub + 1, fname.Length - lsub - 1);
                string[] FN_Ext = fname.Split('.');

                Random r = new Random();
                string F_pre = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + r.Next(10000, 999999).ToString();
                string F_ext = FN_Ext[FN_Ext.Length - 1];

                ReturnDescription = "";

                string NewFileNmae = F_pre + "." + F_ext;

                if (!xImg.UpPic(file, FilePath, NewFileNmae, ref ReturnDescription))
                {
                    Description += "\\r\\n" + ReturnDescription;
                    continue;
                }

                TextBox tb = (TextBox)form1.FindControl(f.Replace("File", "tbDescription"));                

                t_GoodPics.GoodID.Value = Shove._Convert.StrToInt(hfGoodID.Value, -1);
                t_GoodPics.GoodPic_Small.Value = "UpFile/Goods/" + NewFileNmae.Insert(NewFileNmae.IndexOf("."), "_Small");
                t_GoodPics.GoodPic_Big.Value = "UpFile/Goods/" + NewFileNmae;
                t_GoodPics.Description.Value = Shove._Web.Utility.FilteSqlInfusion(tb.Text.Trim());
                t_GoodPics.IsShow.Value = true;

                t_GoodPics.Insert();

                ImageCount++;
            }
        }

        if (ImageCount > 0)
        {
            Shove._Web.JavaScript.Alert(this.Page, "成功上传了" + ImageCount.ToString() + "张图片文件。\\r\\n" + Description, this.Request.Url.AbsoluteUri);

            return;
        }
        else
        {
            Shove._Web.JavaScript.Alert(this.Page, "请选择您要上传的图片。\\r\\n" + Description);

            return;
        }
    }

}
